package cn.z2huo.knowledge.concurrency.synchronizedkeyword.plus;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 *
 * @author z2huo
 */
class NoSafePlusTest {

    /**
     * 线程数量
     */
    private static final int THREAD_COUNT = 10;

    /**
     * 循环次数
     */
    private static final int TURN = 1000;

    public static void main(String[] args) {

        CountDownLatch countDownLatch = new CountDownLatch(THREAD_COUNT);
        NoSafePlus plus = new NoSafePlus();

        Runnable runnable = () -> {
            for (int i = 0; i < TURN; i++) {
//                plus.plus();
                plus.syncPlus();;
            }
            countDownLatch.countDown();
        };

        ExecutorService executorService = Executors.newFixedThreadPool(THREAD_COUNT);

        for (int i = 0; i < THREAD_COUNT; i++) {
            executorService.execute(runnable);
        }
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        System.out.println("期望结果为 " + THREAD_COUNT * TURN);
        System.out.println("实际结果为 " + plus.getAmount());

        executorService.close();
    }
}
